import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.edge.service import Service
import time
from bs4 import BeautifulSoup
import pandas as pd

class Second_classroom(object):
    mobileEmulation = {'deviceName': 'iPhone SE'}
    option = webdriver.EdgeOptions()
    option.add_experimental_option('mobileEmulation', mobileEmulation)
    option.add_experimental_option("detach", True)
    option.add_argument("headless")
    option.add_argument("disable-gpu")
    driver_path = Service(r'msedgedriver.exe')
    # 获取driver对象, 并将配置好的path和option传入进去
    driver = webdriver.Edge(service=driver_path,options=option)
    def __init__(self,school,username,password):
        self.scln = school
        self.usn = username
        self.pwd = password

    def open_web(self):#打开网页
        self.driver.get('https://win.9xueqi.com/')

    def signin(self):#登录
        self.driver.implicitly_wait(10)
        self.driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[2]/div[1]/div[1]/form/div/input').send_keys(
        self.scln)  # 输入学校
        time.sleep(1)
        self.driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[2]/div[2]/div[1]/div').click()  # 先点击div（下拉框）
        time.sleep(1)
        self.driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[3]/div[2]/input').send_keys(self.usn)  # 输入账号
        time.sleep(1)
        self.driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[3]/div[4]/input').send_keys(self.pwd)  # 输入密码
        time.sleep(1)
        self.driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[5]/button').click()
    def search_act(self,actname):#查找活动
        activity = self.driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/div/div/div/div[1]/div[2]/div/input')
        activity.send_keys(actname)  # 输入活动
        activity.send_keys(Keys.ENTER)
    def enroll_act(self):#加入活动
        self.driver.find_element(By.XPATH,'//*[@id="homeSearth"]/div[2]/div[2]/ul/li/a/div[1]/div[2]/div').click()  # 点击活动，进入活动页
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//*[@id="app"]/div[1]/div[8]/div[2]/div').click()  # 点击个人报名
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//*[@id="app"]/div[1]/div[13]/div[2]/div/div[4]').click()  # 点击确认报名

    def list_act(self):#列举活动
        self.driver.find_element(By.XPATH,'/html/body/div[1]/div[1]/div/div/div/div[2]/div/div[2]/div[1]/p[1]/img').click()#点击‘活动’
        time.sleep(1)
        tabel = self.driver.find_element(By.XPATH,'/html/body/div[1]/div[1]/div[2]/div[2]').get_attribute('innerHTML')
        soup = BeautifulSoup(tabel,'html.parser')
        a = soup.find_all('a')
        a_text_list_bg = []
        for row in a:
            row_a_text = row.text
            a_text_list_bg.extend([row_a_text])
        # Extracting 学分, 活动名称, 活动状态, 活动类别, 活动人数, 活动开始时间, 活动结束时间
        credit_list = []
        actname_list = []
        state_list = []
        category_list = []
        people_list = []
        start_time_list = []
        end_time_list = []
        for item in a_text_list_bg:
            # Extracting 学分
            credit_pattern = re.compile(r'\d+\.\d+学分')
            credit_match = credit_pattern.search(item)
            if credit_match:
                credit_list.append(credit_match.group())
            else:
                credit_list.append(None)
            # Extracting 活动名称
            name_match = re.search(r'(?<=学分)(.*?)(?=\n)', item)
            if name_match:
                actname_list.append(name_match.group().strip())
            else:
                actname_list.append(None)
            # Extracting 活动状态
            state_match = re.search(r'[\u4e00-\u9fa5]+中', item)
            if state_match:
                state_list.append(state_match.group())
            else:
                state_list.append(None)
            # Extracting 活动类别
            category_match = re.search(r'中(.*?·.*?) ', item)
            if category_match:
                category_list.append(category_match.group(1).strip())
            else:
                category_list.append(None)
            # Extracting 活动人数
            people_match = re.search(r'(\d+人)', item)
            if people_match:
                people_list.append(people_match.group())
            else:
                people_list.append(None)
            # Extracting 活动时间
            time_match = re.search(r'(\d{4}\.\d{2}\.\d{2} \d{2}:\d{2})—(\d{4}\.\d{2}\.\d{2} \d{2}:\d{2})', item)
            if time_match:
                start_time_list.append(time_match.group(1))
                end_time_list.append(time_match.group(2))
            else:
                start_time_list.append(None)
                end_time_list.append(None)
        #将数据格式化
        data = {
            '活动名称':actname_list,
            '活动学分':credit_list,
            '活动状态':state_list,
            '活动类别':category_list,
            '活动人数':people_list,
            '活动开始时间':start_time_list,
            '活动结束时间':end_time_list,
                }
        #data数据存入activity.csv表
        dataframe = pd.DataFrame(data=data)
        dataframe.to_csv('activity.csv',index=False,sep=',',encoding='utf-8-sig')


